<?php

/**
 * Удаляет учебный разедел.
 *
 */
class Learning_Backend_Categories_Delete extends Backend_Component_Delete
{
    
    /**
     * Реализация обработки пользовательского запроса.
     *
     */
    protected function _delete() 
    {
        $this->_deleteFiles();
        $query = '
            DELETE 
                   `l_c`, `l_a`, `l_a_f`
              FROM 
                   `learning_category` `l_c`
         LEFT JOIN 
                   `learning_aids` `l_a` 
                ON 
                   `l_a`.`cat_id` = `l_c`.`id`
         LEFT JOIN 
                   `learning_aids_files` `l_a_f` 
                ON 
                   `l_a_f`.`aid_id` = `l_a`.`id`
             WHERE 
                   `l_c`.`id` = ' . Application::getRequest()->get('id') . '
            ';
        database::query($query);
        return database::affectedRows();
    }
    
    /**
    * @desc Удаляет файлы, принадлежащие записи.
    * 
    */
    private function _deleteFiles() 
    {
        $query = '
            SELECT 
                   `l_a_f`.`file` 
              FROM 
                   `learning_aids_files` `l_a_f`
         LEFT JOIN 
                   `learning_aids` `l_a` 
                ON 
                   `l_a`.`cat_id` = ' . Application::getRequest()->get('id') . '
             WHERE 
                   `l_a_f`.`aid_id` = `l_a`.`id`';
        foreach (database::fetchCol($query) as $file) {
            @unlink(SITE_ROOT . '/' . Kernel_Config::get('learning', 'UPLOAD_DIR') . database::fetchOne($query));
        }
        database::delete('learning_aids_files', array('aid_id' => Application::getRequest()->get('id')));
    }
    
}
